<template>
	<div class="u-page u-page-color-other">
		<u-navbar title=" " :border-bottom="false" :background="navbar.background" :custom-back="comeBackCustom">
			<view class="slot-wrap">
				<div style="width: 430rpx;">
					<u-search placeholder="输入关键字搜索订单" v-model="keyword" :show-action="false" shape="square" bg-color="#ffffff" @search="search"></u-search>
				</div>
			</view>
		</u-navbar>
		<div style="font-weight: bold;width: 95%;margin: 0 auto;">
			<u-tabs :list="TabsArr" bg-color="#fffbfe" :show-bar="false" active-color="#eb5468" inactive-color="#6b6969"
				 :active-item-style="{fontSize:'34rpx'}" height="100" font-size="30" :current="current" @change="change"></u-tabs>
		</div>
		<div v-if="ordersData && ordersData.length>0">
			<div :class="index == 0?'':'u-mt-10'" style="background-color: #ffffff;width: 95%;margin: 0 auto;border-radius: 10rpx;box-shadow: 5rpx 5rpx 5rpx 5rpx #f3f2f2eb;" v-for="(item,index) in ordersData">
				<div @click="toOrderDetails(item)">
					<div class="u-border-bottom" style="padding: 20rpx 30rpx;display: flex;justify-content: space-between;">
						<div>{{item.createTime?item.createTime:''}}</div>
						<div>{{item.orderStatus?item.orderStatus:''}}</div>
					</div>
					<div class="aui-flex u-mt-10">
						<div class="aui-flex-goods">
							<img :src="item.orderImages.split(',')[0]" alt="">
						</div>
						<div class="aui-flex-box">
							<div class="goods-title">
								{{item.goodsName?item.goodsName:''}}
							</div>
							<div class="goods-specification">{{item.specification?item.specification:''}}</div>
							<div style="padding-top: 15rpx;">
								<u-tag text="商品团购" color="#dc6e00" border-color="#dc6e00" bg-color="#ffffff" size="mini" mode="light" v-if="item.orderType=='购买商品'" />
								<u-tag text="样品推广" color="#40972f" border-color="#40972f" bg-color="#ffffff" size="mini" mode="light" v-if="item.orderType=='领取样品'" />
							</div>
						</div>
					</div>
					<div class="u-pr-15" style="display: flex;flex-direction: row-reverse;">
						<div class="u-flex u-fz-15">
							<div>共1件</div>
							<div class="u-pl-5">
								实付：<span class="u-title">&yen;{{item.orderPrice?item.orderPrice:0.00}}</span>
							</div>
						</div>
					</div>
					<div class="u-pt-10 u-pb-15 u-pr-15" style="display: flex;flex-direction: row-reverse;">
						<div>
							<u-button shape="circle" size="mini" :custom-style="item.orderStatus == '已退款'?customStyle1:customStyle2" @click="toAnotherOrder(item)">再来一单</u-button>
							<u-button shape="circle" size="mini" :custom-style="customStyle2" v-if="item.orderStatus != '已退款'" @click="afterSales(item)">退换/售后</u-button>
							<u-button shape="circle" size="mini" :custom-style="customStyle2" v-if="item.orderStatus == '待收货' || item.orderStatus == '待评价'" @click="toLogisticsInfo(item)">查看物流</u-button>
							<u-button shape="circle" size="mini" :custom-style="customStyle1" v-if="item.orderStatus == '待评价'" @click="toEvaluate(item)">评价</u-button>
							<u-button shape="circle" size="mini" :custom-style="customStyle3" hover-class="none" v-if="item.orderStatus == '已评价' && !item.grade">已评价</u-button>
							<u-button shape="circle" size="mini" :custom-style="customStyle3" hover-class="none" v-if="item.orderStatus == '已评价' && item.grade">{{item.grade}}级</u-button>
							<u-button shape="circle" size="mini" :custom-style="customStyle1" v-if="item.orderStatus == '待发货'" @click="showModifyAddress(item)">修改地址</u-button>
							<u-button shape="circle" size="mini" :custom-style="customStyle1" v-if="item.orderStatus == '待收货'" @click="showConfirmReceipt(item)">确认收货</u-button>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div v-else>
			<div class="u-text-center" style="padding-top: 20%;">
				<u-empty text="暂无数据" mode="data"></u-empty>
			</div>
		</div>
		<!-- 客服 -->
		<u-modal v-model="customerService_show" confirm-text="关闭" confirm-color="#eb5468" title="客服微信">
			<view class="slot-content">
				<div class="u-text-center">欢迎添加【西西】企业微信详询！</div>
				<div class="u-center u-pt-5 u-pb-5">
					<u-image width="300rpx" height="300rpx" :src="customerService_url" @longpress="SaveAlbum(customerService_url)"></u-image>
				</div>
			</view>
		</u-modal>
		<!-- 是否确认收货弹窗提醒 -->
		<u-modal v-model="confirmReceipt_show" confirm-text="确定" confirm-color="#eb5468" 
				@confirm="ConfirmReceipt" title="提示" :mask-close-able="true">
			<view class="slot-content">
				<div class="u-text-center u-pt-20 u-pb-20">是否确认收货</div>
			</view>
		</u-modal>
		<!-- 待发货时修改地址（下单后15分钟内可操作） -->
		<u-modal v-model="modifyAddress_show" confirm-text="确认修改" confirm-color="#eb5468"
				@confirm="ModifyAddress" title="收货地址" :mask-close-able="true">
			<view class="slot-content">
				<div class="u-pt-15 u-pb-15" style="width: 93%;margin: 0 auto;">
					<div style="display: flex;justify-content: space-between;align-items: center;">
						<div class="cont-right">
							<div class="u-flex u-fz-13">
								<span v-if="addressObj.DefaultStatus == 1">
									<div class="default-tag">默认</div>
								</span>
								<span class='address1' v-if="addressObj.Region">{{addressObj.Region.replace(/'-'/g, '')}}-{{addressObj.StreetVillage.replace(/'-'/g, '')}}</span>
							</div>
							<div class="u-title u-fz-20 u-pt-5" v-if="addressObj.Address">{{addressObj.Address}}</div>
							<div class="u-pt-5 u-fz-15">
								<span>{{addressObj.Name}}</span>
								<span class="u-pl-5">{{addressObj.PhoneNum}}</span>
							</div>
						</div>
						<div @click="toSelectAddress">
							<u-icon name="arrow-right" color="#d6d2d2" size="45"></u-icon>
						</div>
					</div>
				</div>
			</view>
		</u-modal>
	</div>
</template>

<script>
	import globalData from "@/globalData";
	export default {
		data() {
			return {
				navbar: {
					title: '订单列表',
					background: {
						backgroundColor: '#f3e4e9',
					}
				},
				TabsArr: [
					{
						name: '全部'
					},
					{
						name: '待发货'
					},
					{
						name: '待收货'
					},
					{
						name: '待评价'
					},
					{
						name: '已退款'
					}
				],
				current: 0,
				pageNum: 1,
				pageSize: 10,
				ordersData: [],
				tips: [],
				activeStyle: {
					color: "#303133"
				},
				barStyle: {
					backgroundColor: "#eb5468"
				},
				TipsShow: false,
				TipsContent: '',
				customStyle1: {
					borderRadius: '20rpx',
					color: '#eb5468',
					marginLeft: '8rpx',
					fontSize: '28rpx',
					padding: '0rpx 20rpx',
					height: '60rpx',
					lineHeight: '60rpx'
				},
				customStyle2: {
					borderRadius: '20rpx',
					marginLeft: '8rpx',
					fontSize: '28rpx',
					padding: '0rpx 20rpx',
					height: '60rpx',
					lineHeight: '60rpx',
					color: '#000000'
				},
				customStyle3: {
					borderRadius: '20rpx',
					marginLeft: '8rpx',
					fontSize: '28rpx',
					padding: '0rpx 20rpx',
					height: '60rpx',
					lineHeight: '60rpx',
				},
				customerService_show: false,//客服弹窗标志
				customerService_url: "https://www-1308272144.cos.ap-guangzhou.myqcloud.com/BPM/202212/FILE/WechatIMG314P9bi1.jpeg",//客服二维码
				EvaluatingId: '',//正在评价的订单id
				confirmReceipt_show: false,//是否确认收货弹窗
				ConfirmReceiptSelected: {},//当前选中进行确认收货的对象
				modifyAddress_show: false,//修改收货地址弹窗
				addressObj: {},//收货地址
				ModifyAddressSelected: {},//当前选中进行修改收货地址的对象
				comeback: '',
				keyword: ''//搜索关键词
			}
		},

		onPullDownRefresh() {
			// 停止Loading
			uni.stopPullDownRefresh();
		},

		onReachBottom() {
			this.pageNum += 1
			this.initOrderList()
		},

		onLoad(option) {
			// 未登录跳转到登录页面
			this.checkLogin();
			if(this.isNotNull(option.comeback)){
				this.comeback = option.comeback;
			}
			this.initOrderList()
			// 获取评完/反馈完成返回的id并更新该条数据的按钮状态
			uni.$on("finishOrder", (orderId) => {
				let index = ''
				for(const i in this.ordersData) {
					if(this.ordersData[i].businessId == orderId){
						index = i
						break
					}
				}
				if(index != ''){
					this.ordersData.splice(index, 1)
				}
			});
			// 选中的收货地址
			uni.$on("AddressObj", (obj = {}) => {
				this.addressObj = obj
			});
		},

		methods: {
			
			/**
			 * uview自定义导航栏返回上一页
			 */
			comeBackCustom(){
				let pages = getCurrentPages()
				if(this.comeback == 1){
					uni.reLaunch({url: '/pages/index/incomeIndex'});
				}else if(pages[pages.length - 2]){
					//如果有上一页，就返回上一页
					this.goBack()
				}else{
					//如果没有上一页，则返回首页
					uni.reLaunch({url:'/pages/index/index'});
				}
			},

			/**
			 * 获取订单记录
			 */
			async initOrderList() {
				const userInfo = uni.getStorageSync('userInfo');
				let res = await this.$u.api.unifyMiniRest({
					systemid: "meily",
					url: "/order/list",
					type: this.current,
					userId: userInfo.userId,
					searchStr: this.keyword,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					loading: false
				});
				if (res.code == 200) {
					if(this.pageNum != 1) {
						this.ordersData = this.ordersData.concat(res.rows)
					} else {
						this.ordersData = res.rows
					}
				} else {
					this.showMSG('error', '出错啦')
				}
			},
			
			/**
			 * 切换tab
			 */
			change(index) {
				this.current = index
				this.pageNum = 1
				this.initOrderList()
			},
			
			/** 
			 * 搜索订单
			 */
			search() {
				this.pageNum = 1
				this.initOrderList()
			},
			
			/**
			 * 点击提示
			 */
			showTips(reason){
				this.TipsContent = reason;
				this.TipsShow = true;
			},
			
			/**
			 * 查看订单详情
			 */
			toOrderDetails(item){
				this.$u.route(item.orderLink);
			},
			
			/**
			 * 点击物流单号跳转到查询物流信息页面
			 */
			toLogisticsInfo(item) {
				if(item.orderType == "购买商品"){
					this.$u.route('/pages_tabbar_contact/common_contact/queryLogisticsInfo?id='+item.businessId+'&logisticsModule=GROUPBUY')
				}else if(item.orderType == "领取样品"){
					this.$u.route('/pages_tabbar_contact/common_contact/queryLogisticsInfo?id='+item.businessId+'&logisticsModule=SAMPLES')
				}
			},
			
			/**
			 * 点击“再来一单”按钮
			 */
			toAnotherOrder(item) {
				// 跳转到销售机会页面
				this.$u.route('/pages_private_scene2/GroupPurchase/DistributionGoods?goodsNo=' + item.goodsNo + '&goodsId=' + item.goodsId)
			},
			
			/** 
			 * 点击“评价”按钮
			 */
			toEvaluate(item) {
				this.EvaluatingId = item.businessId//记录正在评价的订单id，评价完成返回时进行对该条数据的更新
				if(item.orderType == "购买商品"){
					this.$u.route('pages_private_scene2/GroupPurchase/PostComments?recordId='+item.businessId)
				}else if(item.orderType == "领取样品"){
					this.$u.route('pages_private_scene2/provide_samples/trial_feedback?recordId='+item.businessId)
				}
			},
			
			/**
			 * 点击“确认收货”按钮
			 */
			showConfirmReceipt(item) {
				this.ConfirmReceiptSelected = item
				this.confirmReceipt_show = true
			},
			
			/**
			 * 确认收货
			 */
			async ConfirmReceipt() {
				let meilyUrl = ""
				if(this.ConfirmReceiptSelected.orderType == "购买商品"){
					meilyUrl = "/buying/confirmReceipt"
					if(this.ConfirmReceiptSelected.mainId == this.ConfirmReceiptSelected.goodsId){
						// 如果主文档id等于商品id，表示直接购买
						meilyUrl = "/buying/confirmReceipt2"
					}
				}else if(this.ConfirmReceiptSelected.orderType == "领取样品"){
					meilyUrl = "/provide/samples/sub/confirmReceipt"
				}
				let result = await this.$u.api.unifyMiniRest({
					systemid: "meily",
					url: meilyUrl,
					id: this.ConfirmReceiptSelected.businessId,
					loading: false // 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if(result.code == 200){
					this.showMSG("none","已确认收货")
					let index = ''
					for(const i in this.ordersData) {
						if(this.ordersData[i].businessId == this.ConfirmReceiptSelected.businessId){
							index = i
							break
						}
					}
					if(index != ''){
						this.ordersData.splice(index, 1)
					}
				} else {
					this.showMSG("error", "出错啦")
				}
			},
			
			/** 
			 * 点击按钮“修改地址”弹窗
			 */
			async showModifyAddress(item) {
				//判断订单创建时间是否已经超过当前时间10分钟，如果超过则不给修改地址
				let date = new Date(item.createTime.replace(/-/g,"/"))
				if(Date.now() < (date.getTime() + 10*60*1000)){
					this.ModifyAddressSelected = item
				    this.addressObj = JSON.parse(item.address)
					this.modifyAddress_show = true
				}else{
				    this.showMSG('none','订单已经超过了可修改地址的时间')
				}
			},
			
			/** 
			 * 确认修改收货地址
			 */
			async ModifyAddress() {
				if(this.ModifyAddressSelected.orderType == "购买商品"){					let result = await this.$u.api.unifyMiniRest({
						systemid: "meily",
						url: "/buying/modifyReceivingInfo",
						id: this.ModifyAddressSelected.businessId,
						address: JSON.stringify(this.addressObj),
						loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
					});
					if(result.code == 200){
						for(const i in this.ordersData) {
							if(this.ordersData[i].businessId == this.ModifyAddressSelected.businessId){
								this.ordersData[i].address = JSON.stringify(this.addressObj)
								break
							}
						}
						this.showMSG('success','已修改')
						this.modifyAddress_show = false
					}else{
						this.showMSG('error','出错啦')
					}				}else if(this.ModifyAddressSelected.orderType == "领取样品"){
					let consigneeAddress = this.addressObj.Region + "-" + this.addressObj.StreetVillage + " " + this.addressObj.Address
					let result = await this.$u.api.unifyMiniRest({
						systemid: "meily",
						url: "/provide/samples/sub/modifyReceivingInfo",
						id: this.ModifyAddressSelected.businessId,
						consigneeAddress: consigneeAddress,
						consigneeName: this.addressObj.Name,
						consigneePhoneNum: this.addressObj.PhoneNum,
						loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
					});
					if(result.code == 200){
						for(const i in this.ordersData) {
							if(this.ordersData[i].businessId == this.ModifyAddressSelected.businessId){
								this.ordersData[i].address = JSON.stringify(this.addressObj)
								break
							}
						}
						this.showMSG('success','已修改')
						this.modifyAddress_show = false
					}else{
						this.showMSG('error','出错啦')
					}				}
			},
			
			/**
			 * 选择收货地址
			 */
			toSelectAddress() {
				this.$u.route('/pages_tabbar_contact/personal_contact/AddressList?type=select');
			},
			
			/** 
			 * 点击按钮“退换/售后”弹出客服弹窗
			 */
			showCustomerService(){
				this.customerService_show = true
			},
			
			/**
			 * 点击按钮“退换/售后”
			 */
			async afterSales(item){
				if(item.orderType == "购买商品"){// 团购售后
					this.openCustomerServiceChat(globalData.openKfid_afterSales);
				} else if(item.orderType == "领取样品"){// 样品售后
					this.openCustomerServiceChat(globalData.openKfid_sample);
				}
			},
			
			/**
			 * 点击联系客服
			 */
			async openCustomerServiceChat(openKfid) {
				let result = await this.$u.api.unifyMiniRestGet({
					systemid: "meily",
					url: "/qyapi/kf/account/url/".concat(openKfid),
					loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if (result.code == 200) {
					const pages = getCurrentPages(); // 获取栈实例
					//当前页面路径(带参数)
					let currentPage = pages[pages.length - 1]['$page']['fullPath']
					let kfUrl = result.data
					wx.openCustomerServiceChat({
						extInfo: {
							url: kfUrl
						},
						corpId: globalData.corpId,
						showMessageCard: true,
						sendMessagePath: currentPage,
						success(res) {
							console.log(res)
						}
					})
				} else {
					this.showMSG('error', '出错啦！');
				}
			},
			
			/**
			 * 保存到相册
			 */
			SaveAlbum(url) {
				wx.getImageInfo({
				   src: url,
				   success:(res)=> {
					let path = res.path;
					wx.saveImageToPhotosAlbum({
					 filePath:path,
					 success:(res)=> { 
						this.showMSG("success","保存成功！")
					 },
					 fail:(res)=>{
					  console.log("----SaveAlbum fail---")
					  console.log(res);
						this.$u.toast("请点击右上角进入设置并开启添加到相册的权限才能保存到相册噢！")
					 }
					})
				   },
				   fail:(res)=> {
					console.log(res);
				   }
				})
			},
		}

	};
</script>

<style lang="scss" scoped>
	.my-jobs-share {
		font-size: 26rpx;
		width: 170rpx;
		height: 75rpx;
		line-height: 75rpx;
		padding: 0;
		color: #696868;
		border: 1rpx solid #696868 !important;
		background-color: #ffffff;
		float: left;
		margin-right: 1rpx;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-orient: vertical;
		-webkit-box-direction: normal;
		-webkit-flex-direction: column;
		flex-direction: column;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		-webkit-box-pack: center;
		-webkit-justify-content: center;
		justify-content: center;
		padding-left: 0rpx !important;
		padding-right: 0rpx !important;
	}
	
	.slot-content4 {
		font-size: 32rpx;
		text-align: left;
		width: 90%;
		margin: 0 auto;
		padding-top: 60rpx;
		padding-bottom: 60rpx;
	}
	
	.color-red {
		color: red;
	}
	
	.aui-flex {
		display: flex;
		width: 93%;
		margin: 0 auto;
	}
	.aui-flex-goods {
		margin-right: .8em;
		width: 150rpx;
		height: 150rpx;
		line-height: 150rpx;
		text-align: center;
	}
	
	.aui-flex-goods img {
		width: 100%;
		max-height: 100%;
		vertical-align: top;
		border-radius: 15rpx;
	}
	.goods-title {
		width: 470rpx;
		display: -webkit-box;
		/*必须结合的属性,将对象作为弹性伸缩盒子模型显示*/
		-webkit-line-clamp: 1;
		/*设置多少行*/
		-webkit-box-orient: vertical;
		/*必须结合的属性,设置或检索伸缩盒对象的子元素的排列方式*/
		overflow: hidden;
		/*文本会被修剪，并且剩余的部分不可见*/
		text-overflow: ellipsis;
		/*显示省略号来代表被修剪的文本*/
		font-size: 32rpx;
	}
	
	.cont-right {
		display: flex;
		flex-direction: column;
	}
	
	.cont-right p {
		width: 100%;
	}
	
	.default-tag {
		padding: 0rpx 5rpx;
		background-color: #e5392b;
		color: #ffffff;
		border-radius: 5rpx;
		font-size: 20rpx;
		margin-right: 10rpx;
	}
	.address1 {
		width: 450rpx;
		overflow:hidden;
		text-overflow:ellipsis;
		display:-webkit-box;
		-webkit-box-orient:vertical;
		-webkit-line-clamp:1;
	}
	.goods-specification {
		font-size: 30rpx;
		color: #9f9d9e;
		width: 470rpx;		display: -webkit-box;		-webkit-line-clamp: 1;		-webkit-box-orient: vertical;		overflow: hidden;		text-overflow: ellipsis;
	}
	.slot-wrap {
		display: flex;
		align-items: center;
		/* 如果您想让slot内容占满整个导航栏的宽度 */
		flex: 1;
		justify-content: center;
	}
</style>
